from functools import cache


class Solution:

    def numberOf2sInRange(self, n: int) -> int:
        num = [int(v) for v in str(n)]

        @cache
        def f(index: int, ceil: bool, t: int):
            if index == len(num):
                return t

            up = num[index] if ceil else 9
            ans = 0
            for i in range(up + 1):
                ans += f(index + 1, ceil and i == up, t + (i == 2))
            return ans

        return f(0, True, 0)


s = Solution()
print(s.numberOf2sInRange(28675) == 20314)